import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_elm/store/global_data.dart';
import 'package:provider/provider.dart';

import '../components/confirmDialog.dart';
import '../network/user_api.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key, required this.title});
  final String title;

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  TextEditingController _phoneController = TextEditingController();
  TextEditingController _pwdController = TextEditingController();
  GlobalKey _formKey =GlobalKey<FormState>();
  UserApi userApi = UserApi();
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blueAccent.shade400,
        title: Text("${widget.title}",style: TextStyle(color: Colors.white),),
        centerTitle: true,
        // 取消左上角返回箭头
        automaticallyImplyLeading: false,
      ),
      body: Container(
        margin: EdgeInsets.all(15.0),
        child:Form(
          key: _formKey,
          child: Column(
            children: [
              Row(
                children: [
                  Container(
                    width: 75,
                    child:Text("手机号码：", style: TextStyle(color: Colors.grey.shade700, fontWeight: FontWeight.w600),) ,
                  ),
                  Expanded(
                    child: TextFormField(
                      controller: _phoneController,
                      decoration: InputDecoration(
                          hintText: "请输入手机号码",
                          border: InputBorder.none
                      ),
                      validator: (value){
                        if(value!.trim().isEmpty){
                          return "手机号码不能为空";
                        }else if(value.trim().length!=11){
                          return "手机号码位数无效";
                        }
                        return null;
                      },
                    ),
                  )
                ],
              ),
              Row(
                children: [
                  Container(
                    width: 75,
                    child:Text("密码：", style: TextStyle(color: Colors.grey.shade700, fontWeight: FontWeight.w600),) ,
                  ),
                  Expanded(
                    child: TextFormField(
                      controller: _pwdController,
                      obscureText: true,
                      decoration: InputDecoration(
                          hintText: "请输入密码",
                          border: InputBorder.none
                      ),
                      validator: (value){
                        if(value!.isEmpty){
                          return "密码不能为空";
                        }
                        return null;
                      },
                    ),
                  )
                ],
              ),
              Padding(padding: EdgeInsets.only(bottom: 5)),
              Row(
                children: [
                  Expanded(
                    child: ElevatedButton(
                        style: ButtonStyle(
                          shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(5))),
                          backgroundColor: MaterialStateColor.resolveWith((states) {
                            //获取 焦点时/点击时 的颜色
                            if (states.contains(MaterialState.focused) || states.contains(MaterialState.pressed)) {
                              return Colors.green.shade500;
                            }
                            //默认状态使用灰色
                            return Colors.green.shade300;
                          }),
                        ),
                        onPressed: (){
                          login();
                        },
                        child: Text("登录",style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold),)),
                  )
                ],
              ),
              Padding(padding: EdgeInsets.only(bottom: 5)),
              Row(
                children: [
                  Expanded(
                    child: ElevatedButton(
                        style: ButtonStyle(
                          shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(5))),
                          backgroundColor: MaterialStateColor.resolveWith((states) {
                            //获取 焦点时/点击时 的颜色
                            if (states.contains(MaterialState.focused) || states.contains(MaterialState.pressed)) {
                              return Colors.grey.shade300;
                            }
                            //默认状态使用灰色
                            return Colors.grey.shade200;
                          }),
                        ),
                        onPressed: (){
                          Navigator.pushNamed(context, "register");
                        },
                        child: Text("去注册",style: TextStyle(color:Colors.grey.shade700, fontSize: 18, fontWeight: FontWeight.bold),)),
                  )
                ],
              ),

            ],
          ),
        )
      ),
    );
  }

  void login() async{
    if ((_formKey.currentState as FormState).validate()) {
      var res = await userApi.userLogin(_phoneController.text, _pwdController.text);

      await showConfirmDialog(context,"${res.code}:${res.message}");
      if(res.code==200){
        GlobalData globalData = Provider.of<GlobalData>(context, listen: false);
        globalData.changeUserId(res.data!.userId);
        Navigator.pop(context);
        // print("globalData.getUserId(): ${globalData.getUserId()}");
      }

    }
  }
}



